package br.ufpi.hu.prescricao.model;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

@Entity
@Table(name = "usuario", schema = "autenticacao")
@NamedQuery(name="Usuario.findUserByLogin", query="select u from Usuario u where u.login = :login")
@SequenceGenerator(name="usuario_seq", sequenceName="autenticacao.usuario_seq", initialValue=1, allocationSize=1)
public class Usuario {

	public static final String FIND_BY_LOGIN = "Usuario.findUserByLogin";
	
	@Id
	@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="usuario_seq")
	private int id;
	
	@Column(unique = true, nullable = false)
	private String login;
	
	@OneToMany(fetch = FetchType.EAGER, mappedBy = "usuario")
	private Set<Role> roles;
	
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public Set<Role> getRoles() {
		return roles;
	}

	public void setRoles(Set<Role> roles) {
		this.roles = roles;
	}
	
	public void addRole(String role) {
		addRole(new Role(role, "Roles"));
	}
	
	public void addRole(Role role) {
		if (roles==null)
			roles = new HashSet<Role>();
		
		roles.add(role);
	}

	@Override
	public int hashCode() {
		return getId();
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof Usuario){
			Usuario user = (Usuario) obj;
			return user.getId()==(getId());
		}
		
		return false;
	}

	public boolean temRole(String role) {
		
		for (Role roleAtual : roles) {
			
			if (roleAtual.getRole().equals(role))
				return true;
			
		}
		
		return false;
	}

}
